package com.cookie.meetproject.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.cookie.framework.bmob.BmobManger;
import com.cookie.framework.bmob.IMUser;
import com.cookie.framework.helper.PairFriendHelper;
import com.cookie.framework.manager.DialogManager;
import com.cookie.framework.utils.CommonUtils;
import com.cookie.framework.utils.LogUtils;
import com.cookie.framework.view.DialogView;
import com.cookie.framework.view.LoadingView;
import com.cookie.meetproject.R;
import com.cookie.meetproject.adapter.CloudTagAdapter;
import com.cookie.meetproject.model.StarModel;
import com.cookie.meetproject.ui.AddFriendActivity;
import com.cookie.meetproject.ui.QrCodeActivity;
import com.cookie.meetproject.ui.UserInfoActivity;
import com.moxun.tagcloudlib.view.TagCloudView;
import com.uuzuche.lib_zxing.activity.CodeUtils;

import java.util.ArrayList;
import java.util.List;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.FindListener;

/**
 * 项目名:    MeetProject
 * 包名:      com.cookie.meetproject.fragment
 * 文件名:    StartFragment
 * 创建者:    cookie
 * 创建时间:   2020/1/5 0:41
 * 描述:      星球
 */

public class StartFragment extends Fragment implements View.OnClickListener {

    private static final int REQUEST_CODE = 1235;

    private TextView tvStarTitle;
    private ImageView ivCamera;
    private ImageView ivAdd;
    private TextView tvConnectStatus;
    private TagCloudView cloudView;
    private TextView tvRandom;
    private LinearLayout llRandom;
    private TextView tvSour;
    private LinearLayout llSour;
    private TextView tvFate;
    private LinearLayout llFate;
    private TextView tvLove;
    private LinearLayout llLove;

    private List<StarModel> starList = new ArrayList<>();
    private CloudTagAdapter cloudTagAdapter;
    private LoadingView loadingView;

    private DialogView mNullDialogView;
    private TextView tv_null_text;
    private TextView tv_null_cancel;

    private List<IMUser> mAllUserList = new ArrayList<>();

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_star, null);
        initView(view);
        return view;
    }

    private void initView(View view) {
        loadingView= new LoadingView(getActivity());
        loadingView.setCancelable(false);

        mNullDialogView = DialogManager.getInstance().initView(getActivity(), R.layout.layout_star_null_item, Gravity.BOTTOM);
        tv_null_text = mNullDialogView.findViewById(R.id.tv_null_text);
        tv_null_cancel = mNullDialogView.findViewById(R.id.tv_cancel);
        tv_null_cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                DialogManager.getInstance().hide(mNullDialogView);
            }
        });

        tvStarTitle = view.findViewById(R.id.tv_star_title);
        ivCamera = view.findViewById(R.id.iv_camera);
        ivAdd = view.findViewById(R.id.iv_add);
        tvConnectStatus = view.findViewById(R.id.tv_connect_status);
        cloudView = view.findViewById(R.id.cloud_view);
        tvRandom = view.findViewById(R.id.tv_random);
        llRandom = view.findViewById(R.id.ll_random);
        tvSour = view.findViewById(R.id.tv_sour);
        llSour = view.findViewById(R.id.ll_sour);
        tvFate = view.findViewById(R.id.tv_fate);
        llFate = view.findViewById(R.id.ll_fate);
        tvLove = view.findViewById(R.id.tv_love);
        llLove = view.findViewById(R.id.ll_love);

        ivCamera.setOnClickListener(this);
        ivAdd.setOnClickListener(this);

        llRandom.setOnClickListener(this);
        llSour.setOnClickListener(this);
        llFate.setOnClickListener(this);
        llLove.setOnClickListener(this);

        cloudTagAdapter = new CloudTagAdapter(getActivity(), starList);
        cloudView.setAdapter(cloudTagAdapter);

        //监听
        cloudView.setOnTagClickListener((parent, view1, position) -> starUserInfo(starList.get(position).getUserId()));

        PairFriendHelper.getInstance().setOnPairResultListener(new PairFriendHelper.OnPairResultListener() {
            @Override
            public void OnPairListener(String userId) {
                starUserInfo(userId);
            }

            @Override
            public void OnPairFailListener() {
                loadingView.hide();
                Toast.makeText(getActivity(), getString(R.string.text_pair_null), Toast.LENGTH_SHORT).show();
            }
        });

        loadStarUser();
    }

    private void starUserInfo(String userId) {
        loadingView.hide();
        UserInfoActivity.startActivity(getActivity(), userId);
    }

    //加载星球用户
    private void loadStarUser() {
        BmobManger.getInstance().queryAllUser(new FindListener<IMUser>() {
            @Override
            public void done(List<IMUser> list, BmobException e) {
                if (e == null) {
                    if (CommonUtils.isEmpty(list)) {

                        if (mAllUserList.size()>0){
                            mAllUserList.clear();
                        }
                        if (starList.size()>0){
                            starList.clear();
                        }

                        mAllUserList = list;

                        int index = 100;
                        if (list.size() <= 100) {
                            index = list.size();
                        }
                        for (int i = 0; i < index; i++) {
                            IMUser imUser = list.get(i);
                            saveStarUser(imUser.getObjectId(), imUser.getNickName(), imUser.getPhoto());
                        }
                        cloudTagAdapter.notifyDataSetChanged();
                    }
                }
            }
        });
    }

    private void saveStarUser(String userId, String nickName, String photoUrl) {
        StarModel model = new StarModel();
        model.setNickName(nickName);
        model.setPhotoUrl(photoUrl);
        model.setUserId(userId);
        starList.add(model);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_camera:
                //扫描
                Intent intent = new Intent(getActivity(), QrCodeActivity.class);
                startActivityForResult(intent, REQUEST_CODE);
                break;
            case R.id.iv_add:
                startActivity(new Intent(getActivity(), AddFriendActivity.class));
                //添加好友
                break;
            case R.id.ll_random:
                //随机匹配
                pairUser(0);
                break;
            case R.id.ll_sour:
                //灵魂匹配
                if(TextUtils.isEmpty(BmobManger.getInstance().getUser().getConstellation())){
                    tv_null_text.setText(getString(R.string.text_star_par_tips_1));
                    DialogManager.getInstance().show(mNullDialogView);
                    return;
                }

                if(BmobManger.getInstance().getUser().getAge() == 0){
                    tv_null_text.setText(getString(R.string.text_star_par_tips_2));
                    DialogManager.getInstance().show(mNullDialogView);
                    return;
                }

                if(TextUtils.isEmpty(BmobManger.getInstance().getUser().getHobby())){
                    tv_null_text.setText(getString(R.string.text_star_par_tips_3));
                    DialogManager.getInstance().show(mNullDialogView);
                    return;
                }

                if(TextUtils.isEmpty(BmobManger.getInstance().getUser().getStatus())){
                    tv_null_text.setText(getString(R.string.text_star_par_tips_4));
                    DialogManager.getInstance().show(mNullDialogView);
                    return;
                }

                pairUser(1);
                break;
            case R.id.ll_fate:
                //缘分匹配
                pairUser(2);
                break;
            case R.id.ll_love:
                //恋爱匹配
                pairUser(3);
                break;
        }
    }

    //随机匹配规则
    private void pairUser(int index){
        switch (index){
            case 0:
                loadingView.show("随机匹配中...");
                break;
            case 1:
                loadingView.show("灵魂匹配中...");
                break;
            case 2:
                loadingView.show("缘分匹配中...");
                break;
            case 3:
                loadingView.show("异性匹配中...");
                break;
        }
        //计算
       if (CommonUtils.isEmpty(mAllUserList)){
           PairFriendHelper.getInstance().pairUser(index,mAllUserList);
       }else {
           loadingView.hide();
       }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        if (requestCode == REQUEST_CODE) {
            if (null != data) {
                Bundle bundle = data.getExtras();
                if (bundle == null) {
                    return;
                }
                if (bundle.getInt(CodeUtils.RESULT_TYPE) == CodeUtils.RESULT_SUCCESS) {
                    String result = bundle.getString(CodeUtils.RESULT_STRING);
                    LogUtils.i("result：" + result);
                    //Meet#c7a9b4794f
                    if (!TextUtils.isEmpty(result)) {
                        //是我们自己的二维码
                        if (result.startsWith("Meet")) {
                            String[] split = result.split("#");
                            LogUtils.i("split:" + split.toString());
                            if (split != null && split.length >= 2) {
                                try {
                                    UserInfoActivity.startActivity(getActivity(), split[1]);
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                            }
                        } else {
                            Toast.makeText(getActivity(), getString(R.string.text_toast_error_qrcode), Toast.LENGTH_SHORT).show();
                        }
                    } else {
                        Toast.makeText(getActivity(), getString(R.string.text_toast_error_qrcode), Toast.LENGTH_SHORT).show();
                    }

                } else if (bundle.getInt(CodeUtils.RESULT_TYPE) == CodeUtils.RESULT_FAILED) {
                    Toast.makeText(getActivity(), getString(R.string.text_qrcode_fail), Toast.LENGTH_LONG).show();
                }
            }
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        PairFriendHelper.getInstance().disposable();
    }
}
